/*
 * @Author: moeWang
 * @Date: 2021-09-07 13:35:39
 * @LastEditTime: 2021-09-07 15:27:17
 * @LastEditors: moeWang
 * @Description: 单例模式
 * @FilePath: \front-end-design-mode\code\Singleton.js
 */

// 懒汉
console.log('===base===');
var Singleton = function (name) {
    this.name = name
    this.instance = null
}

Singleton.prototype.getName = function () {
    console.log(this.name);
}

Singleton.getInstance = function (name) {
    if (!this.instance) {
        this.instance = new Singleton(name)
    }
    return this.instance
}

var a = Singleton.getInstance('a')
var b = Singleton.getInstance('b')

console.log(a === b); // true
a.getName() // a
b.getName() // a

// 透明版 统一通过new获取单例对象

console.log('===create===');
var createSingleton = (function() {
    let instance
    return function(name) {
        if(instance) {
            return instance
        }
        this.name = name
        return instance = this
    }
})()

createSingleton.prototype.getName = function() {
    console.log(this.name);
}

var c = new createSingleton('c')
var d = new createSingleton('d')

console.log(c === d);
c.getName() // c
d.getName() // c

